package com.mashibing.redis.redis_demo;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.hash.Jackson2HashMapper;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class TestRedis {

    /**
     *
     */
    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    @Qualifier("ooxx")
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    ObjectMapper objectMapper;

    public void testRedis(){
        //高级API
//        redisTemplate.opsForValue().set("hello","hello china");
//        System.out.println(redisTemplate.opsForValue().get("hello"));

        //低级API
//        RedisConnection conn = redisTemplate.getConnectionFactory().getConnection();
//        conn.set("hello02".getBytes(),"mashibing".getBytes());
//        System.out.println(new String(conn.get("hello02".getBytes())));

        //hash类型
//        HashOperations<String, Object, Object> hash = stringRedisTemplate.opsForHash();
//        hash.put("sean", "name", "zhanglei");
//        hash.put("sean", "age", "25");
//        System.out.println(hash.entries("sean"));

        //hash类型 对象转hash
        Person p = new Person();
        p.setAge(16);
        p.setName("zhangSan");
        Jackson2HashMapper jm = new Jackson2HashMapper(objectMapper, false);

//        stringRedisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer<Object>(Object.class));

        stringRedisTemplate.opsForHash().putAll("sean02", jm.toHash(p));
        Map map = stringRedisTemplate.opsForHash().entries("sean02");
        Person person = objectMapper.convertValue(map, Person.class);
        System.out.println(person);

    }
}
